<template>
  <div class="app-container">
    <el-row :gutter="16">
      <!-- ========== 分单流程 ========== -->
      <el-col :span="12">
        <el-card>
          <div slot="header">分单工具</div>
          <el-steps :active="splitStep" finish-status="success" simple>
            <el-step title="1.上传文件"/>
            <el-step title="2.发邮件"/>
          </el-steps>

          <!-- ① 上传 -->
          <div v-if="splitStep===1" style="margin-top:20px">
            <el-upload
              drag
              :limit="1"
              accept=".xlsx"
              :action="splitUploadApi"
              :headers="headers"
              :before-upload="beforeUpload"
              :on-error="onError"
              :show-file-list="true"
              :on-success="splitUploadSuccess">
              <i class="el-icon-upload"/>
              <div>拖拽或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">
                只能上传 xlsx，且不超过 5MB，(文件是要进行分单的订单数据)
              </div>
            </el-upload>
<!--            <el-button type="primary"  @click="splitSendMail" style="margin-top:15px">开始发邮件</el-button>-->
          </div>

          <!-- ② 发邮件进度 -->
          <div v-if="splitStep===2">
            <el-progress :percentage="splitPercent"/>
            <p>{{ splitProgressText }}</p>
            <el-button v-if="splitDone" @click="resetSplit">再导一批</el-button>
          </div>
        </el-card>
      </el-col>

      <!-- ========== 回传订单流程 ========== -->
      <el-col :span="12">
        <el-card>
          <div slot="header">回传订单处理</div>
          <el-steps :active="returnStep" finish-status="success" simple>
            <el-step title="1.抓取订单"/>
            <el-step title="2.下载文件"/>
          </el-steps>

          <!-- ① 抓取 -->
          <div v-if="returnStep===1" style="margin-top:20px">
            <el-date-picker v-model="returnDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"/>
            <el-button type="primary" @click="grabOrder" style="margin-left:10px">抓取回传订单</el-button>
          </div>

          <!-- ② 下载 -->
          <div v-if="returnStep===2">
            <el-alert title="抓取完成" type="success" :closable="false"/>
            <el-button type="success" @click="downloadReturn" style="margin-top:15px">下载回传文件</el-button>
            <el-button @click="resetReturn">再来一次</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listZcsplitorder, getZcsplitorder, delZcsplitorder, uploadZcsplit, updateZcsplitorder } from "@/api/zhongchuangauto/zcsplitorder";
import { getToken } from '@/utils/auth'
import request from '@/utils/request'
import * as XLSX from "xlsx";

export default {
  data() {
    return {
      headers: { Authorization: 'Bearer ' + getToken() },
      /* 分单流程 */
      splitStep: 1,
      splitUploadApi: process.env.VUE_APP_BASE_API + '/common/upload',
      splitPercent: 0,
      splitProgressText: '',
      splitDone: false,
      taskId: '',

      /* 回传流程 */
      returnStep: 1,
      returnDate: this.parseTime(new Date(), '{y}-{m}-{d}'),
      returnFileUrl: ''
    }
  },
  methods: {
    /* ===== 分单 ===== */
    /* 校验文件*/
    beforeUpload(file) {
      const isXlsx = /.(xlsx)$/i.test(file.name)
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isXlsx) this.$message.error('只能上传 xlsx 文件')
      if (!isLt5M) this.$message.error('大小不能超过 5MB')
      return isXlsx && isLt5M
    },

    /* 5.触发上传提交文件动作*/
    submitUpload() {
      // 校验：有没有选文件
      const files = this.$refs.upload.uploadFiles;
      if (!files || files.length === 0) {
        this.$message.warning('请先选择文件');
        return;
      }
      // 手动提交
      this.$refs.upload.submit();
    },
    onError(err){
      this.$message.error('上传失败：' + err.message)
    },
    // 6.上传文件处理
    splitUploadSuccess(res) {
      this.fileUrl = res.url;// 拿到上传文件的url
      this.$message.success('上传成功，开始解析订单数据...');
      // 立即调用后端解析接口
      uploadZcsplit({ fileUrl: res.url }).then( r =>{
          this.$message.success(r.msg);
        }
      );
      this.$message.success('上传成功，请点击【开始发邮件】')
    },
    splitSendMail() {
      if (!this.taskId) { this.$message.warning('请先上传文件'); return }
      this.splitStep = 2
      // 打开 SSE 监听进度
      const evt = new EventSource(process.env.VUE_APP_BASE_API + '/tool/split/progress/' + this.taskId)
      evt.onmessage = e => {
        const d = JSON.parse(e.data)
        if (e.lastEventId === 'done') {
          this.splitPercent = 100
          this.splitProgressText = '邮件全部发送完成'
          this.splitDone = true
          evt.close()
        } else {
          this.splitPercent = Math.round((d.sent / d.total) * 100)
          this.splitProgressText = `已发送 ${d.sent} / ${d.total} 封`
        }
      }
    },
    resetSplit() {
      this.splitStep = 1
      this.splitPercent = 0
      this.splitDone = false
      this.taskId = ''
    },

    /* ===== 回传 ===== */
    grabOrder() {
      request.post('/tool/return/grab', { date: this.returnDate }).then(res => {
        this.returnFileUrl = res.data.url
        this.returnStep = 2
        this.$message.success('抓取完成')
      })
    },
    downloadReturn() {
      window.open(this.returnFileUrl, '_self')
    },
    resetReturn() {
      this.returnStep = 1
    }
  }
}
</script>
